package com.tanhua.dubbo.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.tanhua.dubbo.pojo.Publish;
import com.tanhua.dubbo.pojo.TimeLine;
import com.tanhua.dubbo.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class TimeLineService {

    private final static String TIMELINE_REDIS = "timeline_";

    private final static String FREINEDlIST_REDIS = "friend_";

    private final static String PUBLISH_REDIS = "publish_";


    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 写入好友的时间线表，查询好友列表，进行循环写入
     *
     * @param publish
     * @return
     */
    @Async //异步执行，原理：底层开一个线程去执行该方法
    public CompletableFuture<String> saveTimeLine(Publish publish) {
        //查询好友列表
        try {
            Query query = Query.query(Criteria.where("userId").is(publish.getUserId()));
            List<Users> usersList = this.mongoTemplate.find(query, Users.class);

            //好友的id列表
            List<Object> friendIdList = CollUtil.getFieldValues(usersList, "friendId");
            if (CollUtil.isEmpty(friendIdList)) {
                friendIdList = new ArrayList<>();
            }
            //把自己作为自己的好友
            friendIdList.add(publish.getUserId());

            // 记录当前好友列表 便于补偿
            String timelineRedisKey = this.getFriendListRedisKey(publish.getPid());
            this.redisTemplate.opsForValue().set(timelineRedisKey, StrUtil.join(",", friendIdList));

            for (Object friendId : friendIdList) {
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setPublishId(publish.getId());
                timeLine.setUserId(publish.getUserId());
                timeLine.setDate(System.currentTimeMillis());
                
                //写入到好友时间线
                this.mongoTemplate.save(timeLine, "quanzi_time_line_" + friendId);
                // 记录写入好友时间线进度
                String redisKey = this.getTimelineRedisKey(publish.getPid());
                this.redisTemplate.opsForValue().increment(redisKey);
            }
            return CompletableFuture.completedFuture("ok");
        } catch (Exception e) {
            // 失败的补偿机制（实战中完成）
            String publishJson = JSONUtil.toJsonStr(publish);
            String publishRedis = this.getPublishRedis(publish.getPid());
            this.redisTemplate.opsForValue().set(publishRedis, publish.getId().toString());
            this.rocketMQTemplate.convertAndSend("timeline_topic", publishJson);
            log.error("写入好友的时间线表出错！ publish = {}", publish, e);
        }
        return CompletableFuture.completedFuture("error");
    }

    private String getTimelineRedisKey(Long pid) {
        return TIMELINE_REDIS + pid;
    }

    private String getFriendListRedisKey(Long pid) {return FREINEDlIST_REDIS + pid;}

    private String getPublishRedis(Long pid) {return PUBLISH_REDIS + pid;}


}
